package longrise.phone.com.bjjt_henan.compensate;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.longrise.bjjt.util.UiUtil;

import java.io.ByteArrayOutputStream;

import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.UiUtils;

public class SignatureActivity extends Activity implements OnClickListener
{
	//重签
	private Button signature_btn1;
	//确定
	private Button signature_btn2;
	//title
	private TextView tv_title;
	//返回
	private LinearLayout btn_back;
	//请在此区域签名
	private RelativeLayout signature_rl;
	private PaintView mView;
	private FrameLayout frameLayout;

	private int width;
	private int height;
	private boolean ismove=false;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.responsibility_signature_main);
		initView();
		regEvent(true);
	}

	@SuppressWarnings("deprecation")
	private void initView() {
		signature_btn1 = (Button)findViewById(R.id.signature_btn1);
		signature_btn2 = (Button)findViewById(R.id.signature_btn2);
		tv_title = (TextView)findViewById(R.id.tv_title);
		btn_back = (LinearLayout)findViewById(R.id.hn_btn_back);
		signature_rl = (RelativeLayout)findViewById(R.id.signature_rl);
		frameLayout = (FrameLayout) findViewById(R.id.signatureview);
		/*WindowManager wm = this.getWindowManager();
	     width = wm.getDefaultDisplay().getWidth();
	     height = wm.getDefaultDisplay().getHeight();*/
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		width = dm.widthPixels;//宽度
		height = dm.heightPixels ;//高度

		mView = new PaintView(this);
		frameLayout.addView(mView);
	}

	private void regEvent(boolean b) {
		if(null != signature_btn1) {
			signature_btn1.setOnClickListener(b==true ? this : null);
		}
		if(null != signature_btn2) {
			signature_btn2.setOnClickListener(b==true ? this : null);
		}
		if(null != tv_title) {
			tv_title.setOnClickListener(b==true ? this : null);
		}
		if(null != btn_back) {
			btn_back.setOnClickListener(b==true ? this : null);
		}
		if(null != signature_rl) {
			signature_rl.setOnClickListener(b==true ? this : null);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		signature_btn1 = null;
		signature_btn2 = null;
		tv_title = null;
		btn_back = null;
		signature_rl = null;
		mView = null;
		frameLayout = null;

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.hn_btn_back :
			onDestroy();
			finish();
			break;
		case R.id.signature_btn1 :
			//重签
			ismove=false;
			mView.clear();
			break;
		case R.id.signature_btn2 :
			//如果签名过短，无法确定，提示重签
			if(!ismove){
				UiUtil.showToast(SignatureActivity.this, "请签名后再点击确定");
				return;
			}
			//确定
			Bitmap b = mView.getCachebBitmap();
			//新调整的bitmap的宽高
			Bitmap newbitmap=changeBitmapWH(b);
			Bitmap bp = codec(newbitmap, CompressFormat.JPEG,80);
			//Bitmap bp = codec(b,Bitmap.CompressFormat.JPEG,80);
		/*	Bitmap bp1 = codec(b,Bitmap.CompressFormat.JPEG,80); //旧的bitmap的宽高 
			Log.e("test", bp.getWidth()+":"+bp.getHeight());
			Log.e("test", bp1.getWidth()+":"+bp1.getHeight());*/
			 ByteArrayOutputStream baos = new ByteArrayOutputStream();
			 bp.compress(CompressFormat.JPEG, 100, baos);
	         byte[] bitmapBytes = baos.toByteArray();
			Intent intent = new Intent();
			intent.putExtra("bitmap", bitmapBytes);
			this.setResult(RESULT_OK, intent);
			this.onDestroy();
			this.finish();
			break;
		case R.id.signature_rl :
			//点击开始画画
			signature_rl.setVisibility(View.GONE);
			frameLayout.setVisibility(View.VISIBLE);
			mView.requestFocus();
			break;
		default:
			break;
		}
	}

	private Bitmap codec(Bitmap bitmap, CompressFormat format, int quality) {
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        bitmap.compress(format, quality, baos);
        byte[] data=baos.toByteArray();
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }


	class PaintView extends View {
		private Paint paint;
		private Canvas cacheCanvas;
		private Bitmap cachebBitmap;
		private Path path;

		public Bitmap getCachebBitmap() {
			return cachebBitmap;
		}

		public PaintView(Context context) {
			super(context);
			init();
		}

		private void init() {
			paint = new Paint();
			paint.setAntiAlias(true);
			paint.setStrokeWidth(15);
			paint.setStyle(Paint.Style.STROKE);
			paint.setColor(Color.BLACK);
			path = new Path();
			//转换画布的宽高
			int[] chmap = changeBitmapWHBig();
			cachebBitmap = Bitmap.createBitmap(chmap[0], chmap[1], Config.ARGB_8888);
			Log.e("test", cachebBitmap.getWidth()+":::"+cachebBitmap.getHeight());
			cacheCanvas = new Canvas(cachebBitmap);
			cacheCanvas.drawColor(getResources().getColor(R.color.white));//画布的颜色
		}

		public void clear() {
			if (cacheCanvas != null) {
				paint.setColor(Color.WHITE);
				cacheCanvas.drawPaint(paint);
				paint.setColor(Color.BLACK);
				cacheCanvas.drawColor(Color.WHITE);
				invalidate();
			}
		}

		@Override
		protected void onDraw(Canvas canvas) {
			// canvas.drawColor(BRUSH_COLOR);
			canvas.drawBitmap(cachebBitmap, 0, 0, null);
			canvas.drawPath(path, paint);
		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {

			int curW = cachebBitmap != null ? cachebBitmap.getWidth() : 0;
			int curH = cachebBitmap != null ? cachebBitmap.getHeight() : 0;
			if (curW >= w && curH >= h) {
				return;
			}

			if (curW < w)
				curW = w;
			if (curH < h)
				curH = h;

			Bitmap newBitmap = Bitmap.createBitmap(curW, curH, Config.ARGB_8888);
			Canvas newCanvas = new Canvas();
			newCanvas.setBitmap(newBitmap);
			if (cachebBitmap != null) {
				newCanvas.drawBitmap(cachebBitmap, 0, 0, null);
			}
			cachebBitmap = newBitmap;
			cacheCanvas = newCanvas;
		}

		private float cur_x, cur_y;
		@SuppressLint("ClickableViewAccessibility")
		@Override
		public boolean onTouchEvent(MotionEvent event) {

			float x = event.getX();
			float y = event.getY();

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				cur_x = x;
				cur_y = y;
				path.moveTo(cur_x, cur_y);
				break;
			}
			case MotionEvent.ACTION_MOVE: {
				path.quadTo(cur_x, cur_y, x, y);
				cur_x = x;
				cur_y = y;
				if(cur_x>2.0&&cur_y>2.0){
					ismove=true;  //判断是否书写文字
				}
				break;
			}
			case MotionEvent.ACTION_UP: {
				cacheCanvas.drawPath(path, paint);
				path.reset();
				break;
			}
			}
			invalidate();
			return true;
		}
	}
	//签名160*90的bitmap
	private Bitmap changeBitmapWH(Bitmap b) {
		int width2 = b.getWidth();
		int height2 = b.getHeight();
		//获取较小的倍数
		int times=1;
		/*int times1=width2 / 160;
		int times2=height2 / 90;
		if(times1<=times2){
			times=times1;
		}else{
			times=times2;
		}*/
		//返回的bitmap的宽高
		int newWidth = 160*times;
		int newHeight =90*times;
		//计算缩放比例
		float scaleWidth = ((float) newWidth) / width2;
		float scaleHeight = ((float) newHeight) / height2;

		//想要缩放的宽高
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap changeBitmap = Bitmap.createBitmap(b, 0, 0, width2, height2, matrix, true);
		Log.e("test", changeBitmap.getWidth()+"???"+changeBitmap.getHeight());
		return changeBitmap;
	}
	//根据屏幕的宽高，获得最接近160*90的倍数的画布的bitmap的宽高
	private int[] changeBitmapWHBig(){
		//获取较小的倍数
		int times=1;
		int times1=width / 160;
		int times2=height / 90;
		if(times1<=times2){
			times=times2;
		}else{
			times=times1;
		}
		//返回的bitmap的宽高
		int newWidth = 160*times;
		int newHeight =90*times;
		return new int[] {newWidth,newHeight};
	}
}